package com.only4play.auth.security.authentication.admin.password;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.only4play.auth.security.model.PasswordLoginRequest;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zlm
 * @date 2024/1/24
 */
public class AdminPasswordLoginProcessFilter extends AbstractAuthenticationProcessingFilter {

  protected AdminPasswordLoginProcessFilter( AuthenticationManager authenticationManager) {
    super("/admin/auth/passwordLogin", authenticationManager);
  }

  @Override
  public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {

    ObjectMapper mapper = new ObjectMapper();
    //拿到请求
    PasswordLoginRequest loginRequest = mapper.readValue(httpServletRequest.getInputStream(), PasswordLoginRequest.class);
    //转为token
    AdminPasswordToken token = new AdminPasswordToken(loginRequest.getUsername(), loginRequest.getPassword());
    //然后找到provider
    return this.getAuthenticationManager().authenticate(token);

  }
}
